package thinkinginjava.IO;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Reader;

public class TxtReplaceMachine {
	private static final String ENCODE = "UTF-8";
	private String sTxt;
	private String tTxt;
	private String input;
	private String output;
	private static final String TEXT = "<>c<>";
	public TxtReplaceMachine(String sTxt, String tTxt, String input,
			String output) {
		this.sTxt = sTxt;
		this.tTxt = tTxt;
		this.input = input;
		this.output = output;
	}

	public void matchAndReplace() throws IOException {
		Reader reader = new FileReader(new File(input));
		char[] cbuf = new char[4096];
		StringBuffer content = new StringBuffer();
		int p = 0;
		while((p = reader.read(cbuf)) > 0) {
			content.append(cbuf, 0, p);
		}
		
		OutputStream out = new FileOutputStream(output);
		
		out.write(content.toString().replaceAll(sTxt, tTxt).getBytes(ENCODE));
		out.close();
	}
 
	
	public static void main(String[] args) throws IOException {
		TxtReplaceMachine m = new TxtReplaceMachine("\\b中文\\b", "c", "D:\\my_codes\\mydemos\\src\\main\\java\\thinkinginjava\\IO\\TxtReplaceMachine.java", "D:\\my_codes\\mydemos\\src\\main\\java\\thinkinginjava\\IO\\TxtReplaceMachine.java");
		m.matchAndReplace();
	}
	
}

